﻿using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;

public class AlipayNotify
{
    private string _input_charset = "";
    private string _key = "";
    private string _partner = "";
    private string _sign_type = "";
    private string _transport = "";
    private string gateway = "";
    private string mysign = "";
    private string responseTxt = "";
    private ArrayList sPara = new ArrayList();

    public AlipayNotify(ArrayList inputPara, string notify_id, string partner, string key, string input_charset, string sign_type, string transport)
    {
        this._transport = transport;
        if (this._transport == "https")
        {
            this.gateway = "https://www.alipay.com/cooperate/gateway.do?";
        }
        else
        {
            this.gateway = "http://notify.alipay.com/trade/notify_query.do?";
        }
        this._partner = partner.Trim();
        this._key = key.Trim();
        this._input_charset = input_charset;
        this._sign_type = sign_type.ToUpper();
        this.sPara = AlipayFunction.Para_filter(inputPara);
        this.sPara.Sort();
        this.mysign = AlipayFunction.Build_mysign(this.sPara, this._key, this._sign_type, this._input_charset);
        this.responseTxt = this.Verify(notify_id);
    }

    private string Get_Http(string strUrl, int timeout)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(strUrl);
            request.Timeout = timeout;
            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            StringBuilder builder = new StringBuilder();
            while (-1 != reader.Peek())
            {
                builder.Append(reader.ReadLine());
            }
            return builder.ToString();
        }
        catch (Exception exception)
        {
            return ("错误：" + exception.Message);
        }
    }

    private string Verify(string notify_id)
    {
        string strUrl = "";
        if (this._transport == "https")
        {
            strUrl = this.gateway + "service=notify_verify&partner=" + this._partner + "&notify_id=" + notify_id;
        }
        else
        {
            strUrl = this.gateway + "partner=" + this._partner + "&notify_id=" + notify_id;
        }
        return this.Get_Http(strUrl, 0x1d4c0);
    }

    public string Mysign
    {
        get
        {
            return this.mysign;
        }
    }

    public string ResponseTxt
    {
        get
        {
            return this.responseTxt;
        }
    }
}

